<template>
  <!-- 版本管理 -->
  <div class="version">
    <el-row>
      <el-col style="margin-right: 10px" class="content-left">
        <el-row class="handleBox">
          <el-col :span="18">
            <template>
              <el-button type="normal" @click="design">设计</el-button>
              <el-button type="normal" @click="publish">发布</el-button>
              <el-button type="normal" @click="delFunc()">删除</el-button>
              <el-button type="normal" @click="suspend()">锁定</el-button>
              <el-button type="normal" @click="activate()">激活</el-button>
              <el-button type="normal" @click="run()">启动</el-button>
              <el-button type="normal" @click="copy()">复制</el-button>
            </template>
          </el-col>
          <el-col :span="6">
            <div class="handleIconBox">
              <el-popover
                placement="bottom"
                width="150"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="operation_checkbox">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox
                      v-for="item in textData"
                      :label="item.label"
                      :key="item.prop"
                      >{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <i
                  class="iconfont icon-liebiaoshezhi"
                  title="列表设置"
                  slot="reference"
                ></i>
              </el-popover>
            </div>
          </el-col>
        </el-row>
        <el-table
          ref="multipleTable"
          :data="tableData"
          @row-click="authorizeFor"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="processDefName"
            label="流程名称 "
            v-if="columnState[0]"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="deployStatus"
            label="发布状态 "
            align="center"
            v-if="columnState[1]"
            :filter-method="(val, row) => row.deployStatus == val"
            :filters="[
              { text: '已发布', value: '1' },
              { text: '未发布', value: '0' },
            ]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.deployStatus == 1">
                <i class="startState"></i><span>已发布</span>
              </div>
              <div v-if="scope.row.deployStatus == 0">
                <i class="unStartState"></i
                ><span style="color: red">未发布</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态 "
            v-if="columnState[2]"
            :filter-method="(val, row) => row.status == val"
            :filters="[
              { text: '已激活', value: '1' },
              { text: '已锁定', value: '0' },
            ]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.status == 1">
                <i class="startState"></i><span>已激活</span>
              </div>
              <div v-if="scope.row.status == 0">
                <i class="unStartState"></i
                ><span style="color: red">已锁定</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="processDefVersion"
            label="版本号"
            sortable
            v-if="columnState[3]"
            :formatter="(row) => row.processDefVersion || '-'"
          >
          </el-table-column>
          <el-table-column
            prop="lastUpdateTime"
            label="最后修改时间"
            sortable
            v-if="columnState[4]"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div v-if="scope.row.lastUpdateTime">
                {{ timeFormat(scope.row.lastUpdateTime) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
            <el-table-column
            prop="description"
            label="描述"
            v-if="columnState[5]"
            :formatter="(row) => row.description || '-'"
            show-overflow-tooltip
          >
          </el-table-column>
        </el-table>
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          @refresh="searchFunc"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <!-- 流程定义弹窗 -->
    <el-dialog
      top
      :title="designTitles[0]"
      :visible.sync="designVisible"
      width="80%"
      append-to-body
    >
      <!-- 流程设计页面 -->
      <slot name="-" style="border: none;padding: 0px;margin: 0px;">
      <bpmn ref="bpmn" :row="row" product="flowable" @processSave="processSave"></bpmn>
      </slot>
    </el-dialog>
  </div>
</template>

<script>
import bpmn from "./bpmn/VueBpmn.vue"; // 流程设计页面new
import moment from "moment";
import { workflow } from "@/api/index";
export default {
  props: {
    processDefCodeVersion: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      profOp: 'edit',
      defId: '',
      profId: '',
      row: {},
      addOrEdit: false, // 新增/编辑/查看弹窗
      serachMore: false,
      isProConfig: false, //工程表配置弹窗
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      saveTitles: ["新增流程定义", "编辑流程定义", "复制流程定义"],
      designTitles: ["流程设计"],
      designVisible: false,
      statusList: [
        { value: "1", label: "已激活" },
        { value: "0", label: "已锁定" },
      ],
      moduleDataForm: {},
      searchOrgTip: "",
      // save表单机构树悬停提示
      saveOrgTip: "",
      searchForm: {
        processDefCode: "",
        page: 1,
        size: 15,
      },
      total: 100,
      saveForm: {
        processDefCode: "",
        processDefName: "",
        status: "1",
      },
      searchFF: {},
      saveFormRules: {
        processDefCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[A-Z_]{3,3}$/,
            message: "只能输入3位的大写英文字母",
            trigger: "blur",
          },
          { validator: this.currencyCodeValid, trigger: "blur" },
        ],
        processDefName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9（）()\[\]【】{}]{1,15}$/,
            message: "只能输入1-15位的汉字、字母、数字或括号",
            trigger: "blur",
          },
        ],
      },
      checkList: [],
      // 列隐藏
      textData: [
        { label: "流程名称" },
        { label: "发布状态" },
        { label: "状态" },
        { label: "版本号" },
        // { label: "创建人" },
        { label: "最后修改时间" },
        { label: "描述" }
      ],
      // 获取table的数据
      tableData: [],
      //编辑行内数据暂存，供判断表单状态
      editRow: {},
    };
  },
  components: {
    bpmn,
  },
  created() {
  },
  computed: {
    columnState() {
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    },
  },
  mounted() {
    // this.getList();
  },
  watch: {
    addOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    },
  },
  methods: {
     // 保存流程图
   processSave(data) {
      console.log(data,'保存的流程图数据')
      const self = this
          workflow.saveProcessDesign(data).then(res => {
            if (res.code === 200) {
               this.designVisible = false
                self.$message.success("流程保存成功")
                this.searchFunc()
            } else{
              this.$message.error(res.message|| "保存失败")
            }
          })
    },

    //
    // 复制此流程
    copy(){
       let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择要复制的数据");
      }
      this.$confirm("您确定要复制选中数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            description: selection[0].description,
            modelCode: selection[0].processDefCode,
            modelId: selection[0].processDefId,
            modelName: selection[0].processDefName 
          }
          workflow.processCopy(data).then((res) => {
            if (res.code == 200) {
              this.$message.success( res.message || "复制成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });



     
    },
    checkListInit() {
      this.checkList = this.textData.map((v) => {
        return v.label;
      });
    },
    searchFunc() {
      this.searchForm.processDefCode = this.processDefCodeVersion;
      let data = this.searchForm;
      workflow.queryDefForPage(data).then((res) => {
        this.tableData = res.datas.rows;
        this.total = res.datas.total;
      });
    },
    design() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行设计");
      }
      console.log("进入流程设计页面");
      const processDesignId = selection[0].processDefId
      this.row = selection[0]
      this.profOp = 'edit'
      this.defId = this.row.processDefId
      this.profId = this.row.processDefCode
      this.designVisible = true;
      // 调用工作流的初始化接口
      setTimeout(()=>{
      this.$refs.bpmn.init(this.row)
      },50)
    },
    editFunc() {
      this.saveFlg = 2;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      let form = { ...row };
      this.editRow = form;
      this.saveForm = form;
      this.addOrEdit = true;
    },
    // 编号是否重复校验
    currencyCodeValid(rule, value, callback) {
      // 只在新增时校验
      if (this.saveFlg != 1) {
        callback();
        return;
      }
      publicManage_pub
        .currencyManagecheckCurrencyCodeUnique({ processDefCode: value })
        .then((res) => {
          if (res.success) {
            callback(new Error("编号已存在"));
          } else {
            callback();
          }
        });
    },
    saveFunc() {
      this.$refs["saveForm"].validate((valid) => {
        if (valid) {
          let data = {
            ...this.saveForm,
          };
          publicManage_pub.currencyManageSave(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.addOrEdit = false;
              this.searchFunc();
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });
        }
      });
    },
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = { ids: selection.map((v) => v.processDefId) };
          workflow.delProcessDef(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 启动
    run(){
       let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      this.$confirm(`您确定要启动所选流程吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            processDesignId: selection[0].processDefId,
          };
          workflow.startById(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });

    },
    // 激活
    activate() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      this.$confirm(`您确定要激活所选流程吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            processDesignId: selection[0].processDefId,
          };
          workflow.processActivate(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 锁定
    suspend() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      this.$confirm(`您确定要锁定所选流程吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            processDesignId: selection[0].processDefId,
          };
          workflow.processSuspend(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "成功");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 发布
    publish() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      this.$confirm(`您确定要发布所选流程吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            processDesignId: selection[0].processDefId,
          };
          workflow.deployProcess(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "发布失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    

    authorizeFor(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleRowSelection(row, true);
      }
      this.userName = row.roleName;
    },
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchForm.page = val;
      this.searchFunc();
    },
  },
};
</script>

<style lang="scss" scoped>
.version{
  min-height: 380px;
  margin-bottom: 20px;
}
.dialogSearchBox {
  header {
    text-align: center;
    span {
      margin: 0 20px;
    }
  }
}
/deep/.el-dialog__body {
  max-height: 700px;
}
</style>